//处理图像识别的服务
const tf = require('@tensorflow/tfjs-node');
const fs = require('fs');

class AIService {
  constructor() {
    this.model = null;
    this.labels = ['apple', 'banana', 'beef']; // 100+食材
  }

  async loadModel() {
    this.model = await tf.loadGraphModel('file://./model/model.json');
  }

  async recognizeIngredients(imagePath) {
    // 图像预处理
    const imageBuffer = fs.readFileSync(imagePath);
    const tensor = tf.node.decodeImage(imageBuffer)
      .resizeNearestNeighbor([224, 224])
      .div(tf.scalar(255.0))
      .expandDims();

    // 预测并返回top3结果
    const predictions = this.model.predict(tensor);
    const top3 = tf.topk(predictions, 3);
    return top3.indices.dataSync().map(i => this.labels[i]);
  }
}

module.exports = new AIService();